﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace SimpleServiceBus.EndpointMonitor.Web.Helpers.Flot
{
    public static class FlotHtmlHelperExtensions
    {
        //Flot Helpers
        public static string PlotThatFlot(this HtmlHelper<FlotChartViewData> helper, string dataVariableName)
        {
            var plot = new StringBuilder();
            plot.AppendFormat("$.plot($(\"#{0}\"),{1}", helper.ViewData.Model.ChartDivId, dataVariableName);
            
            string globals = helper.ViewData.Model.GlobalOptions.ToFlotJson();
            if (!String.IsNullOrEmpty(globals))
            {
                plot.AppendFormat(",{0}", PlotOptions(helper));
                
            }
            
            plot.Append(");");
            
            return plot.ToString();
        }

        public static string DataQueryStringParameters(this HtmlHelper<FlotChartViewData> helper)
        {
            var parms = new List<string>();
            
            if (helper.ViewData.Model.SeriesOptions != null)
            {
                foreach (string seriesName in helper.ViewData.Model.SeriesOptions.Keys)
                {
                    parms.Add(HttpUtility.UrlEncode(seriesName) + "=" +
                              HttpUtility.UrlEncode(helper.ViewData.Model.SeriesOptions[seriesName].ToFlotJson()));
                }
            }

            if (helper.ViewData.Model.ReturnCaptions)
                parms.Add("returnCaptions=true");

            if (helper.ViewData.Model.ReturnIdentifiers)
                parms.Add("returnIdentifiers=true");

            if (helper.ViewData.Model.Pivot)
                parms.Add("pivot=true");

            parms.Add("discreteAxis=" + helper.ViewData.Model.DiscreteAxis);

            return String.Join("&", parms.ToArray());
        }


        public static string PlotOptions(this HtmlHelper<FlotChartViewData> helper)
        {
            if (helper.ViewData.Model.GlobalOptions != null)
                return helper.ViewData.Model.GlobalOptions.ToFlotJson();
            return String.Empty;
        }

        public static string DataUrl(this HtmlHelper<FlotChartViewData> helper)
        {
            string queryString = DataQueryStringParameters(helper);
            if (!String.IsNullOrEmpty(queryString))
                return helper.ViewData.Model.DataUrl + "&" + queryString;
            return helper.ViewData.Model.DataUrl;
        }
    }
}